package com.zhsj.OkeHomeConsumption.ui.fragment.minehome;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.dialog.MessageDialog;
import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.empty.RecordListBean;
import com.zhsj.OkeHomeConsumption.empty.ShopListBean;
import com.zhsj.OkeHomeConsumption.ui.activity.RestaurantActivity;
import com.zhsj.OkeHomeConsumption.ui.fragment.indexhome.IndexHomeFragment;
import com.zhsj.OkeHomeConsumption.ui.fragment.minehome.mvp.BailPresenter;
import com.zhsj.OkeHomeConsumption.ui.fragment.minehome.mvp.BailUIInterFace;
import com.zhsj.OkeHomeConsumption.ui.fragment.minehome.mvp.BailtwoPresenter;
import com.zhsj.OkeHomeConsumption.ui.fragment.minehome.mvp.BailtwoUIInterFace;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.zhsj.OkeHomeConsumption.common.Constants.SHARED_PERFERENCE_USERINFO;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 区域运营商/商家审核通过后保证金
 */
public final class BailtwoActivity extends MyActivity implements BailtwoUIInterFace {

    @BindView(R.id.price_text)
    TextView priceText;
    @BindView(R.id.bujiao_ben)
    Button bujiaoBen;
    @BindView(R.id.tiqu_btn)
    Button tiquBtn;
    @BindView(R.id.guize_lin)
    LinearLayout guizeLin;
    @BindView(R.id.recy)
    RecyclerView recy;


    private BailtwoPresenter mBailPresenter;

    private String deposit;//最高保证金 ,
    private String depositLow;//最低保证金 ,
    private String depositRate;//每笔抽成比例 ,

    //用户信息实体
    private FormalUserInfo userInfo = null;

    //保证金支付记录
    private List<RecordListBean> RecordList = null;
    private double totalDeposit = 0.0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bailtwo;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_copy_title;
    }

    @Override
    protected void initView() {
        userInfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);
        mBailPresenter = new BailtwoPresenter(getActivity(), this);
    }

    @Override
    protected void initData() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recy.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        mBailPresenter.BailGettwo(userInfo.getLifeUserDTO().getApplyCopartnerType() == 0 ? userInfo.getLifeUserDTO().getLifeType() : userInfo.getLifeUserDTO().getApplyCopartnerType());
        mBailPresenter.BailGet(userInfo.getLifeUserDTO().getApplyCopartnerType() == 0 ? userInfo.getLifeUserDTO().getLifeType() : userInfo.getLifeUserDTO().getApplyCopartnerType());

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.bujiao_ben, R.id.tiqu_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
//            case R.id.jiaona_button:
//                //pay_flage 标识支付类型（0 支付保证金）
//
//                startActivity(new Intent(this, SecurityDepositActivity.class)
//                        .putExtra("depositHigh", deposit)
//                        .putExtra("depositLow", depositLow)
//                        .putExtra("depositRate", depositRate));
//                finish();
//                break;
            case R.id.bujiao_ben:
                if(deposit.equals("0.0")&&depositLow.equals("0.0")){
                 toast("保证金已交完");
                }else{
                    startActivity(new Intent(this, BailInputPriceActivity.class).putExtra("price", deposit).putExtra("depositLow",depositLow));
                }
                break;
            case R.id.tiqu_btn:
                new MessageDialog.Builder(getActivity())
                        .setTitle("提交申请") // 标题可以不用填写
                        .setMessage("申请提取保证金\n保证金提取后，取消您的运营权限")
                        .setConfirm("确定")
                        .setCancel("取消") // 设置 null 表示不显示取消按钮
                        //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                        .setListener(new MessageDialog.OnListener() {

                            @Override
                            public void onConfirm(Dialog dialog) {
                                mBailPresenter.ExtractDeposit(userInfo.getLifeUserDTO().getApplyCopartnerType() == 0 ? userInfo.getLifeUserDTO().getLifeType() : userInfo.getLifeUserDTO().getApplyCopartnerType());
                                dialog.dismiss();
                            }

                            @Override
                            public void onCancel(Dialog dialog) {
                                dialog.dismiss();
                            }
                        })
                        .show();
                break;
        }
    }

    /**
     * 获取保证金
     */

    @Override
    public void BailGet(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonarr = jsonOBJ.optJSONObject("data");
                // 数据对接正常
                JSONArray jsonArray = jsonarr.optJSONArray("recordList");
                totalDeposit = jsonarr.optDouble("totalDeposit");
                if(totalDeposit==0.0){
                    tiquBtn.setVisibility(View.GONE);
                }
                if(jsonArray!=null){
                    RecordList = new Gson().fromJson(jsonArray.toString(), new
                            TypeToken<ArrayList<RecordListBean>>() {
                            }.getType());
                    ShopAdapter  shopadper = new ShopAdapter();
                    recy.setAdapter(shopadper);
                }

                String deposit = jsonarr.optString("totalDeposit");
                priceText.setText("¥" + deposit);
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("BailGet", "获取保证金异常");
        }
    }

    @Override
    public void BailGettwo(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonarr = jsonOBJ.optJSONObject("data");
                // 数据对接正常
                deposit = jsonarr.optString("depositHigh");
                depositLow = jsonarr.optString("depositLow");
                depositRate = jsonarr.optString("depositRate");
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("BailGet", "获取保证金异常");
        }
    }

    @Override
    public void ExtractDeposit(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                startActivityFinish(ExtractBailActivity.class);
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("ExtractDeposit", "提取保证金异常");
        }
    }

    public class ShopAdapter extends BaseQuickAdapter<RecordListBean, BaseViewHolder> {
        public ShopAdapter() {
            super(R.layout.item_bailinputprice, RecordList);
        }

        @Override
        protected void convert(BaseViewHolder helper, final RecordListBean item) {

            if(item.getPayDeduction()==1){
                helper.setText(R.id.name_text, "代扣保证金");
            }else{
                //  `pay_type`  '支付方式--1-连连，2-微信，3-积分',
                switch (item.getPayType()){
                    case 1:
                        helper.setText(R.id.name_text, "连连支付");
                        break;
                    case 2:
                        helper.setText(R.id.name_text, "微信支付");
                        break;
                    case 3:
                        helper.setText(R.id.name_text, "收益扣除");
                    case 4:
                        helper.setText(R.id.name_text, "支付宝支付");
                        break;
                    case 5:
                        helper.setText(R.id.name_text, "线下现金汇款");
                        break;
                }
            }
            helper.setText(R.id.timer_text, item.getCreateTime())
                    .setText(R.id.price_text, "+"+item.getMoneyOrder());

        }
    }
}